<template>
  <view class="view-class">
    <u-navbar back-text="返回" title="宿舍检查"></u-navbar>
    <view class="view-box">
      <u-form :model="form" ref="uForm" label-width="180" label-align="center">
        <u-form-item required label="宿舍楼栋" prop="building"><u-input v-model="form.building" disabled /></u-form-item>
        <u-form-item required label="房间号" prop="roomId"><u-input v-model="form.roomId"  disabled /></u-form-item>
        <u-form-item required label="城市" prop="cityName"><u-input v-model="form.cityName" type="select" disabled /></u-form-item>
        <u-form-item required label="地址"  prop="residenceAddress"><u-input v-model="form.residenceAddress" type="textarea" :auto-height="true"  disabled /></u-form-item>
<!--        <u-form-item required label="站点" prop="deptId"><u-input v-model="form.deptId" type="textarea"  disabled/></u-form-item>-->
        <u-form-item required label="宿管" prop="supervisor"><u-input v-model="form.supervisor" disabled /></u-form-item>
<!--        <u-form-item required label="站长" prop="nickName"><u-input v-model="form.nickName"   /></u-form-item>-->
        <u-form-item required label="安全员" prop="securityOfficer"><u-input v-model="form.securityOfficer"  disabled  /></u-form-item>
        <u-form-item required label="情况上报" prop="situationReport"><u-input v-model="form.situationReport"  type="textarea" :auto-height="true" /></u-form-item>
        <u-form-item required label="已入住人数" prop="checkInNumber"><u-input v-model="form.checkInNumber"   /></u-form-item>
        <u-form-item required label="总床位数" prop="bedTotal"><u-input v-model="form.bedTotal"   /></u-form-item>
        <u-form-item required label="宿舍客厅照片（至少2张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160" :header="uploadHeader"  :action="clUplodUrl" @on-remove="uploadRemove" @on-success="uploadSuccess"
                     ref="handIdCardUpload" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍房间照片（至少5张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160"  :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove2" @on-success="uploadSuccess2"
                     ref="handIdCardUpload2" ></u-upload>
        </u-form-item>
        <u-form-item required label="卫生间照片（至少2张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160"  :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove3" @on-success="uploadSuccess3"
                     ref="handIdCardUpload3" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍厨房照片（至少2张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160"  :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove4" @on-success="uploadSuccess4"
                     ref="handIdCardUpload4" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍阳台照片（至少2张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160"  :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove5" @on-success="uploadSuccess5"
                     ref="handIdCardUpload5" ></u-upload>
        </u-form-item>
        <u-form-item required label="灭火器检查（至少2张）" prop="bedImages">
          <u-upload :source-type="['camera']" width="160" height="160"  :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove6" @on-success="uploadSuccess6"
                    ref="handIdCardUpload6" ></u-upload>
        </u-form-item>
        <u-form-item required label="视频上传" prop="dormitoryVideo">
          <cl-upload  v-model="videoList" cloudType="other" :compressed="true" :headers="uploadHeader" :listStyle="{
              columns: 2,
              columnGap: '20rpx',
              rowGap:'20rpx',
              height:'166rpx',
              radius:'20rpx'
          }" :action="clUplodUrl2"  :maxVideo="1" @onSuccess="onSuccess" fileType="video" :sourceType="['camera']">
            <template v-slot:addImg>
              <view class="newAddImg">
                <u-icon  name="plus" size="40"></u-icon>
                <text >选择视频</text>
              </view>
            </template>
          </cl-upload>
        </u-form-item>
      </u-form>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc" v-if="!isSuccess">提交</u-button>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('success')" v-else>完成</u-button>
    </view>
    <u-select v-model="showContactRelationSel" :list="contactRelationList" mode="single-column"
              @confirm="selectedContactRelation"></u-select>
    <u-top-tips ref="uTips"></u-top-tips>
    <u-modal v-model="show" confirm-text="退出"
             title="提示"  @confirm="submitFunc('success')"
    >
      <view class="u-update-content">
        <rich-text style="text-align: center;padding: 30rpx" :nodes="content"></rich-text>
      </view>
    </u-modal>
  </view>
</template>
<script>
import {compressImg} from '@/utils/compressor/compress.js'
import {uploadImg} from '@/utils/upload.js'
import {isEmpty} from "@/utils";
import * as consts from "@/utils/constant.js";
import clUpload from '../../../uni_modules/cl-upload/components/cl-upload/cl-upload.vue'
// import uniRate from '@/uni_modules/uni-rate/'
export default {
  components:{
    clUpload
  },
  data() {
    return {
      show:false,
      content:'未查询到宿舍信息，暂时无法操作！',
      rules:{
        building: [{required: true,message: '请输入楼栋号',trigger: ['change','blur'],}],
        residenceAddress: [{required: true,message: '请输入地址',trigger: ['change','blur'],}],
        cityName: [{required: true,message: '请选择城市',trigger: ['change','blur'],}],
        roomId: [{required: true,message: '请输入房间号',trigger: ['change','blur'],}],
        supervisor: [{required: true,message: '请输入宿管',trigger: ['change','blur'],}],
        securityOfficer: [{required: true,message: '请输入安全员',trigger: ['change','blur'],}],
        situationReport: [{required: true,message: '请输入情况上报',trigger: ['change','blur'],}],
        checkInNumber: [{required: true,message: '请输入已入住人数',trigger: ['change','blur'],}],
        bedTotal: [{required: true,message: '请输入总床位数',trigger: ['change','blur'],}],
        dormitoryVideo: [{required: true,message: '请上传宿舍视频',trigger: ['change','blur'],}],
      },
      form: {},
      sexList: [
        {
          name: '男',
          checked: false,
          disabled: false
        },
        {
          name: '女',
          checked: false,
          disabled: false
        }
      ],
      checkboxList: [
        {
          name: '是',
          checked: false,
          disabled: false
        },
        {
          name: '否',
          checked: false,
          disabled: false
        },
      ],
      radio: '',
      switchVal: false,
      showImages:false,
      showIdCardBadgeImages:false,
      showIdCardPortraitImgPreview:false,
      idCardPopup:true,
      idCardForm:{},
      isCRM:false,
      calendarShow:false,
      mode: 'date',
      //同行人员相关
      // 关系列表
      contactRelationList: [],
      showContactRelationSel:false,
      tzryPopup:false,
      tzryForm:{},
      isSuccess:false,
      videoList:[],
      fileList:[],
      fileList2:[],
      fileList3:[],
      fileList4:[],
      fileList5:[],
      fileList6:[],
      clUplodUrl:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/maintain/signUpload',
      clUplodUrl2:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/maintain/uploadVideo',
      dormitoryId:'',
      uploadHeader:{
        Authorization:"Bearer " + uni.getStorageSync("token")
      }
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  async onLoad(query) {
    this.dormitoryId = query.dormitoryId
    let res3 = await this.$api.dormitory.getShowDormitory(this.dormitoryId)
    let data = res3.data
    if (isEmpty(data) || isEmpty(data.ridersDormitory)) {
      this.show = true
      return
    }
    this.form = Object.assign({},data.sysUser,data.ridersDormitory)
    this.form.dormitoryId = this.dormitoryId
    let securityOfficer = uni.getStorageSync("securityOfficer")
    if (securityOfficer) {
      this.form.securityOfficer = securityOfficer.nickName
    }
    // this.contactRelationList = []
    // let res = await this.$api.dormitory.getdictType('repairs_project');
    // let data2 = res.data
    // if (data2) {
    //   data2.forEach(item => {
    //     this.contactRelationList.push({ value: item.dictValue, label: item.dictLabel })
    //   })
    // }

  },
  methods:{
    repairsProjectFunc(){
      this.showContactRelationSel = true
    },
    uploadRemove(index, lists, name) {
      console.log(index, lists, name)
      delete this.fileList[index]
      this.fileList = this.fileList.filter(v => {
        return v
      })
    },
    uploadRemove2(index, lists, name) {
      delete this.fileList2[index]
      this.fileList2 = this.fileList2.filter(v => {
        return v
      })
    },
    uploadRemove3(index, lists, name) {
      delete this.fileList3[index]
      this.fileList3 = this.fileList3.filter(v => {
        return v
      })
    },
    uploadRemove4(index, lists, name) {
      delete this.fileList4[index]
      this.fileList4 = this.fileList4.filter(v => {
        return v
      })
    },
    uploadRemove5(index, lists, name) {
      delete this.fileList5[index]
      this.fileList5 = this.fileList5.filter(v => {
        return v
      })
    },
    uploadRemove6(index, lists, name) {
      delete this.fileList6[index]
      this.fileList6 = this.fileList6.filter(v => {
        return v
      })
    },
    uploadSuccess(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:2
      }
      this.fileList.push(param)
    },
    uploadSuccess2(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:3
      }
      this.fileList2.push(param)
    },
    uploadSuccess3(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:4
      }
      this.fileList3.push(param)
    },
    uploadSuccess4(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:5
      }
      this.fileList4.push(param)
    },
    uploadSuccess5(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:6
      }
      this.fileList5.push(param)
    },
    uploadSuccess6(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:7
      }
      this.fileList6.push(param)
    },
    beforeUpload(tempFile) {
      // console.log('beforeUpload',tempFile)
      // if (tempFile.duration < 60)  return  uni.showToast({title:'视频录制时长不足，最低录制60秒',icon:'none',duration:2000})
    },
    onSuccess(result){
      this.$set(this.form, 'dormitoryVideo', result.fileName);
      this.videoList.push((window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + result.fileName)
    },
    jointUrl(url) {
      // return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/')
      return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + url
    },
    selectedContactRelation(e){
      this.form.repairsProject = e[0].value
      this.form.repairsProject2 = e[0].label
    },
    async submitFunc(type) {
      if (type == 'success') {
        setTimeout(()=>{
          uni.reLaunch({
            url: `/pages/serve/cleaning/loginWebIndex?role=3`
          })
        },600)
        return
      }

      let flag = {flag : true,num:0}
      let flag2 = {flag : true,num:0}
      let flag3 = {flag : true,num:0}
      let flag4 = {flag : true,num:0}
      let flag5 = {flag : true,num:0}
      let flag6 = {flag : true,num:0}
      let fileList = [...this.fileList,...this.fileList2,...this.fileList3,...this.fileList4,...this.fileList5,...this.fileList6]
      fileList.forEach(v=>{
        if (v.type == 2){
          flag.flag = false
          flag.num++
        }
        if (v.type == 3){
          flag2.flag = false
          flag2.num++
        }
        if (v.type == 4){
          flag3.flag = false
          flag3.num++
        }
        if (v.type == 5){
          flag4.flag = false
          flag4.num++
        }
        if (v.type == 6){
          flag5.flag = false
          flag5.num++
        }
        if (v.type == 7){
          flag6.flag = false
          flag6.num++
        }
      })
      if (flag.flag || flag.num < 2) return uni.showToast({title:"请上传宿舍客厅照片至少2张",icon: "error",});
      if (flag2.flag || flag2.num <5) return uni.showToast({title:"请上传宿舍房间照片至少5张",icon: "error",});
      if (flag3.flag || flag3.num < 2) return uni.showToast({title:"请上传宿舍卫生间照片至少2张",icon: "error",});
      if (flag4.flag || flag4.num < 2) return uni.showToast({title:"请上传宿舍厨房照片至少2张",icon: "error",});
      if (flag5.flag || flag5.num < 2) return uni.showToast({title:"请上传宿舍阳台照片至少2张",icon: "error",});
      if (flag6.flag || flag6.num < 2) return uni.showToast({title:"请上传灭火器照片至少2张",icon: "error",});
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          uni.showLoading({
            title: '申请中'
          });
          let openId = uni.getStorageSync('openId')
          this.form.openId = openId
          const {code,msg,data} = await this.$api.dormitory.addHealth(this.form).catch((e)=>{
          })
          let num = 0
          if (code == 200) {
            fileList.forEach((v,i)=>{
              v.healthId = data
              v.openId = openId
              this.$api.dormitory.addPictureHealth(v).catch((e)=>{})
              num++
            })
            console.log('num,this.fileList.length',num,this.fileList.length)
            if (num >= this.fileList.length) {
              uni.showToast({
                title: '提交成功',
                icon: "none",
              });
              setTimeout(()=>{
                uni.reLaunch({
                  url: `/pages/serve/cleaning/loginWebIndex?role=3`
                })
              },600)
              this.isSuccess = true
              uni.hideLoading();
            }
          }
        } else {
          console.log('验证失败');
        }
      });
    },
    dateInterval(Time){
      // 获取今天的日期
      const today = new Date();
      const specifiedDateStr = Time;
      const specifiedDate = new Date(specifiedDateStr);
      const timeDiff = today.getTime() - specifiedDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      return daysDiff
    },
    nowTime(){
      const now = new Date();
      // 获取年、月、日
      const year = now.getFullYear();
      let month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份是从 0 开始计数的，使用padStart方法补零
      let day = now.getDate().toString().padStart(2, '0'); // 获取日期，使用padStart方法补零
      return year+'-'+month+'-'+day
    },
    changeCalendar(e) {
      const nowTime = this.nowTime()
      if (e.result != nowTime) {
        this.form.checkOutTime = e.result
      } else {
        this.form.checkOutTime =  '';
        uni.showToast({
          title: "离宿日期不可选择当天",
          icon: "none",
        });
      }
    },
    checkOutTimeFunc() {
      console.log(11)
      this.calendarShow = true
    },
    async confirmFunc() {
      console.log(this.$api)
      let { code, msg ,data } = await this.$api.dormitory.getRidInfoByIdCard(this.idCardForm.idCardNo).catch(()=>{});
      if (data){
        function judgeGender(idNumber) {
          // 获取身份证号的倒数第二位数字
          const genderDigit = parseInt(idNumber.charAt(idNumber.length - 2));
          // 判断性别
          if (genderDigit % 2 === 0) {
            return '女';
          } else {
            return '男';
          }
        }
        this.form.sex = judgeGender(data.idCardNo)
        this.isCRM = true
        let NewForm = Object.assign({},data,JSON.parse(JSON.stringify(this.form)));
        this.form = JSON.parse(JSON.stringify(NewForm))
        this.$forceUpdate();
      }
      this.idCardPopup = false
    },
    cancelFunc() {

    },
    radioGroupChange(){

    },
    // 删除身份证人像面
    onIdCardBadgeImgDelete() {
      this.form.idCardBadgeImages = null
      this.showIdCardBadgeImages = false
    },
    // 删除身份证国徽面
    onIdCardPortraitImgDelete() {
      this.form.idCardPortraitImages = null
      this.showIdCardPortraitImgPreview = false
    },
    //删除人脸照片
    onHandIdCardImgDelete(item,index) {
      delete this.fileList[index]
      this.fileList = this.fileList.filter(v =>{ return v })
      this.showImages = false
    },
    // 上传图片
    async uploadPic(file, name,type) {
      try {
        const res = await uploadImg(file,'/xsdcrm-wechat-api/wxseparateAgreement/signUpload',false);
        let param = {
          maintainId:'',
          damageItem:res.fileName,
          status:type
        }
        this.fileList.push(param)
      } catch (e) {
      }
    },
    // 照片选择后回调
    onHandIdCardChooseCallback(lists) {
      // 压缩图片
      compressImg({
        file: lists[0].file, success: (result) => {
          this.uploadPic(result,'repairsImage',1)
          this.showImages = true
        }
      })
    },
  }
};
</script>
<style scoped>
*{
  box-sizing: border-box;
}
.view-class{
  width: 100%;
  height: 100vh;
}
.view-box{
  padding:0 30rpx;
  padding-bottom: 120rpx;
}
.container {
  height: 200vh;
  margin-top: 150rpx;
}

.sticky {
  width: 750rpx;
  height: 120rpx;
  background-color: #2979ff;
  color: #fff;
  padding: 24rpx;
}
.u-form-item{
  padding-right: 30rpx;
}

/deep/.u-star-wrap{
  line-height: 1;
}
.newAddImg{
  width:166rpx;
  height: 166rpx;
  overflow: hidden;
  margin: 5px;
  background: #f4f5f6;
  position: relative;
  border-radius: 5px;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
/deep/.u-input__textarea{
  min-height: auto!important;
}
</style>
